package com.doubao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.user.constant.UserConstant;
import com.doubao.user.dto.request.UserFeedbackRequest;
import com.doubao.user.entity.UserFeedback;
import com.doubao.user.mapper.UserFeedbackMapper;
import com.doubao.user.service.UserFeedbackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 用户反馈服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserFeedbackServiceImpl extends ServiceImpl<UserFeedbackMapper, UserFeedback> implements UserFeedbackService {

    private final UserFeedbackMapper userFeedbackMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> submitFeedback(Long userId, UserFeedbackRequest request) {
        if (userId == null || request == null || StringUtils.isBlank(request.getType()) || StringUtils.isBlank(request.getContent())) {
            return Result.failed("参数错误");
        }

        try {
            UserFeedback feedback = new UserFeedback();
            feedback.setUserId(userId);
            feedback.setType(request.getType());
            feedback.setContent(request.getContent());
            feedback.setContact(request.getContact());
            feedback.setStatus(UserConstant.FEEDBACK_STATUS_PENDING);
            feedback.setCreatedAt(LocalDateTime.now());
            feedback.setUpdatedAt(LocalDateTime.now());

            userFeedbackMapper.insert(feedback);
            return Result.success();
        } catch (Exception e) {
            log.error("提交反馈失败", e);
            return Result.failed("提交反馈失败");
        }
    }

    @Override
    public IPage<UserFeedback> getUserFeedbacks(Long userId, int page, int size) {
        if (userId == null) {
            return new Page<>();
        }

        LambdaQueryWrapper<UserFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFeedback::getUserId, userId)
                .orderByDesc(UserFeedback::getCreatedAt);

        Page<UserFeedback> pageQuery = new Page<>(page, size);
        return userFeedbackMapper.selectPage(pageQuery, wrapper);
    }

    @Override
    public UserFeedback getFeedbackById(Long feedbackId) {
        if (feedbackId == null) {
            return null;
        }
        return userFeedbackMapper.selectById(feedbackId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> markAsProcessed(Long feedbackId) {
        if (feedbackId == null) {
            return Result.failed("反馈ID不能为空");
        }

        try {
            userFeedbackMapper.markAsProcessed(feedbackId);
            return Result.success();
        } catch (Exception e) {
            log.error("标记反馈为已处理失败", e);
            return Result.failed("标记反馈为已处理失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> replyFeedback(Long feedbackId, String reply) {
        if (feedbackId == null || StringUtils.isBlank(reply)) {
            return Result.failed("参数错误");
        }

        try {
            userFeedbackMapper.replyFeedback(feedbackId, reply);
            return Result.success();
        } catch (Exception e) {
            log.error("回复反馈失败", e);
            return Result.failed("回复反馈失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteFeedback(Long feedbackId) {
        if (feedbackId == null) {
            return Result.failed("反馈ID不能为空");
        }

        try {
            userFeedbackMapper.deleteById(feedbackId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除反馈失败", e);
            return Result.failed("删除反馈失败");
        }
    }

    @Override
    public IPage<UserFeedback> getAllFeedbacks(Integer status, String type, int page, int size) {
        LambdaQueryWrapper<UserFeedback> wrapper = new LambdaQueryWrapper<>();

        if (status != null) {
            wrapper.eq(UserFeedback::getStatus, status);
        }

        if (StringUtils.isNotBlank(type)) {
            wrapper.eq(UserFeedback::getType, type);
        }

        wrapper.orderByDesc(UserFeedback::getCreatedAt);

        Page<UserFeedback> pageQuery = new Page<>(page, size);
        return userFeedbackMapper.selectPage(pageQuery, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> batchMarkAsProcessed(Long[] feedbackIds) {
        if (feedbackIds == null || feedbackIds.length == 0) {
            return Result.failed("反馈ID列表不能为空");
        }

        try {
            for (Long feedbackId : feedbackIds) {
                userFeedbackMapper.markAsProcessed(feedbackId);
            }
            return Result.success();
        } catch (Exception e) {
            log.error("批量标记反馈为已处理失败", e);
            return Result.failed("批量标记反馈为已处理失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> batchReplyFeedback(Long[] feedbackIds, String reply) {
        if (feedbackIds == null || feedbackIds.length == 0 || StringUtils.isBlank(reply)) {
            return Result.failed("参数错误");
        }

        try {
            for (Long feedbackId : feedbackIds) {
                userFeedbackMapper.replyFeedback(feedbackId, reply);
            }
            return Result.success();
        } catch (Exception e) {
            log.error("批量回复反馈失败", e);
            return Result.failed("批量回复反馈失败");
        }
    }
}